package zcatt.examples.jface.demos;

import static java.lang.System.out;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.*;

public class ProgressMonitorDialogDemo {

	public static void main(String[] args) {
		Display display = new Display();
		Shell shell = new Shell(display);
		shell.setText("ProgressMonitorDialogDemo");
		shell.setSize(800, 600);		
		shell.open();
		
		out.println("main UI thread= "+ Thread.currentThread().getId());
		out.println("threadCount= "+ Thread.activeCount());

		ProgressMonitorDialogDemo inst = new ProgressMonitorDialogDemo(shell);
		inst.run();
		
		while(!shell.isDisposed())
			if(!display.readAndDispatch())
				display.sleep();
		
		display.dispose();
	}
	
	ProgressMonitorDialog dialog;
	
	public ProgressMonitorDialogDemo(Shell parent)
	{
		dialog = new ProgressMonitorDialog(parent);		
	}
	
	public void run()
	{
		IRunnableWithProgress runnable = monitor -> {
			
			out.println("worker thread= "+ Thread.currentThread().getId());
			out.println("threadCount= "+ Thread.activeCount());
			
			IProgressMonitor blocking = monitor;			

			blocking.beginTask("doing...", 100);
			for (int i = 0; i < 10; i++) {
				blocking.setBlocked(new Status(IStatus.WARNING, "Blocked", "blocked..."));
				blocking.worked(5);
				Thread.sleep(500);
				blocking.clearBlocked();
				blocking.worked(5);
				Thread.sleep(500);
				if (monitor.isCanceled())
					return;
			}
			blocking.done();			
		};
		
		try {
			out.println("before run(), threadCount= "+ Thread.activeCount());
			dialog.run(true, true, runnable);			//此处发起单独thread执行runnable
			out.println("after run(), threadCount= "+ Thread.activeCount());
		} catch (InvocationTargetException | InterruptedException e) {
			e.printStackTrace();
		}
	}

}
